package cn.com.dcsgo.controller;

import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * ConsumerController
 *
 * @author Dcsgo
 * @since 2025/2/18 16:50
 */
@RestController
public class ConsumerController {
    private final RestTemplate restTemplate;
    private final NacosServiceDiscovery serviceDiscovery;

    @GetMapping("/nacos/consumer/{str}")
    public String getService(@PathVariable("str") String str) throws NacosException {
        ServiceInstance serviceInstance = serviceDiscovery.getInstances("quickstart-provider").get(0);
        String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
        return restTemplate.getForObject("http://" + url + "/nacos/service/" + str, String.class);
    }

    public ConsumerController(RestTemplate restTemplate, NacosServiceDiscovery serviceDiscovery) {
        this.restTemplate = restTemplate;
        this.serviceDiscovery = serviceDiscovery;
    }
}
